package com.ruoyi.controller;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.config.DelayedQueueConfig;
import com.ruoyi.service.OrderService;
import com.ruoyi.utils.MapUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * @Author: star
 * @Description:
 * @DateTime: 2023/8/11 21:26
 **/
@RestController
@RequestMapping("/seller/order")
public class OrderController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/shoppingGoods")
    public AjaxResult getShoppingList() {
        // 从Redis中获取参数值
        String goodsIdKey = "goodsId";
        String idKey = "id";

        Integer cachedGoodsId = (Integer) redisTemplate.opsForValue().get(goodsIdKey);
        Integer cachedId = (Integer) redisTemplate.opsForValue().get(idKey);

        // 判断Redis的缓存值是否为空
        if (cachedGoodsId != null && cachedId != null){
            return AjaxResult.success(orderService.getShoppingList(cachedGoodsId,cachedId));
        }else {
            return AjaxResult.error("缓存中的cachedGoodsId 或 cachedId为空!");
        }
    }

//  拿到redis中的购物车商品数据分组
    @GetMapping("/getRedisGoods")
    public AjaxResult getRedisGoods(){
        Map map = redisService.getCacheMap("member"+32);
        List<Map<String,List>> list=new ArrayList<Map<String,List>>();
        Set<String> set=new HashSet<>();
        for (Object key : map.keySet()) {
            Object result = map.get(key);
            if (result instanceof Map) {
                Object warehouseCode = ((Map<String, Object>) result).get("warehouseCode");
                set.add(warehouseCode.toString());
            }
        }
        for (Iterator<String> it = set.iterator(); it.hasNext(); ) {
            String warehouseCode = it.next();
            Map<String,List> m1=new HashMap<>();
            List arrayList = new ArrayList<>();
            for (Object key : map.keySet()) {
                Object result = map.get(key);
                if (result instanceof Map) {
                    Object wCode = ((Map<String, Object>) result).get("warehouseCode");
                    if(wCode.equals(warehouseCode)){
                        arrayList.add(result);
                    }
                }
            }
            m1.put(warehouseCode.toString(),arrayList);
            list.add(m1);
        }
        return AjaxResult.success(list);
    }
//  获取缓存token信息
    @GetMapping("/getTokenMessage")
    public AjaxResult getTokenMessage(){
        Object map = redisService.getCacheObject("login:1");
        return AjaxResult.success(map);
    }
//    用接口增加账户余额
    @GetMapping("/updateAmount")
    public AjaxResult updateAmount(Integer id){
        Map<String,Object> map = orderService.test(id);
        redisService.setCacheObject("login:"+id,map);
        return AjaxResult.success(map);
    }
//    从缓存中删除某个仓库下的所有商品
    @PostMapping("/delArray")
    public void delArray(@RequestBody List<Map<String, Object>> list){
        System.out.println(list);
        for (int i = 0; i < list.size(); i++) {
            Map<String,Object> map = list.get(i);
            int specificationId = Integer.parseInt(map.get("specificationId").toString());
            redisService.deleteCacheMapValue("member" + 32, "goodsSpecificationId" + specificationId);
        }
    }
//    购物车加减数量修改redis中的商品的数量
    @PostMapping("alterNum")
    public void alterNum(@RequestBody Map<String,Object> map){
        int specificationId = Integer.parseInt(map.get("specificationId").toString());
        if (Integer.parseInt(map.get("buyNum").toString()) >0 ){
            redisService.setCacheMapValue("member" + 32, "goodsSpecificationId" + specificationId,map);
        }else if (Integer.parseInt(map.get("buyNum").toString()) == 0 ){
            redisService.deleteCacheMapValue("member" + 32, "goodsSpecificationId" + specificationId);
        }
    }
//    订单创建成功从redis中删除多个商品
    @PostMapping("alterNums")
    public void alterNums(@RequestBody List<Map<String,Object>> list){
        for (int i = 0; i < list.size(); i++) {
            Map<String,Object> map = list.get(i);
            int specificationId = Integer.parseInt(map.get("specificationId").toString());
            redisService.deleteCacheMapValue("member" + 32, "goodsSpecificationId" + specificationId);
        }
    }
//    获取经纬度之间距离m
    @PostMapping("/getGeoDistance")
    public double getGeoDistance(@RequestBody Map<String,Object> map){
        double lat1 = Double.parseDouble(map.get("lat1").toString());
        double lng1 = Double.parseDouble(map.get("lon1").toString());
        double lat2 = Double.parseDouble(map.get("lat2").toString());
        double lng2 = Double.parseDouble(map.get("lon2").toString());
        return MapUtils.GetDistance(lat1,lng1,lat2,lng2);
    }
//    创建订单
    @PostMapping("/addOrder")
    public AjaxResult addOrder(@RequestBody Map<String,Object> map){
        String result = orderService.addOrder(map, (List<Map<String, Object>>) map.get("list"));
        return result.length() >0 ? AjaxResult.success(result): AjaxResult.error();
    }

    @GetMapping("/getOrder")
    public AjaxResult getOrder(){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("uuid", IdUtil.simpleUUID());
        return new AjaxResult().success(map);
    }
    @PostMapping("/sendDelayedMsg")
    public void sendDelayedMsg(String message) {
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME, DelayedQueueConfig.DELAYED_ROUTING_KEY, "------消息来自ttl为:" + "(ms)的队列" + message, msg -> {
            msg.getMessageProperties().setDelay(5000);
            return msg;
        });
    }
//    支付订单 去调度
    @PostMapping("/payOrder")
    public AjaxResult payOrder(@RequestBody Map<String,Object> map){
        boolean result = orderService.payOrder(map);
        return new AjaxResult().success(result);
    }
//    验证支付密码是否正确
    @PostMapping("/password")
    public AjaxResult password(@RequestBody Map<String,Object> map){
        return orderService.password(map) ? AjaxResult.success(): AjaxResult.error();
    }
}
